package net.wanho.service.impl;

import cn.hutool.core.util.IdUtil;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.RequiredArgsConstructor;
import net.wanho.constant.CaptchaConstant;
import net.wanho.service.CaptchaService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Author：汤小洋
 * Date：2023-10-07 16:32
 * Description：<描述>
 */
@Service
@RequiredArgsConstructor
public class CaptchaServiceImpl implements CaptchaService {

    private final StringRedisTemplate redisTemplate;

    @Override
    public Map<String, Object> captcha() {
        Captcha captcha = new ArithmeticCaptcha(); // 算术验证码

        // 生成一个临时用户id，对应用户的验证码
        String uuid = IdUtil.simpleUUID();

        // 将验证码保存到redis中
        redisTemplate.opsForValue().set(CaptchaConstant.CAPTCHA_PREFIX +uuid, captcha.text(), CaptchaConstant.CAPTCHA_EXPIRE, TimeUnit.MINUTES);

        Map<String,Object> map = new HashMap<>();
        map.put("uuid", uuid);
        map.put("img", captcha.toBase64());
        return map;
    }

    @Override
    public void check(String uuid, String code) {
        // 获取redis中的验证码
        String key = CaptchaConstant.CAPTCHA_PREFIX + uuid;
        String trueCode = redisTemplate.opsForValue().get(key);

        if(StringUtils.isEmpty(trueCode)){
            throw new RuntimeException("验证码已过期！");
        }

        // 删除验证码
        redisTemplate.delete(key);

        if (!trueCode.equalsIgnoreCase(code)){
            throw new RuntimeException("验证码错误！");
        }

    }

}
